﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestWizardsForms
{
    public static class TabControlHelper
    {
        public static void HideTabPage(this TabControl control,  TabPage tp)
        {
            if (control.TabPages.Contains(tp))
                control.TabPages.Remove(tp);
        }


        public static void ShowTabPage(this TabControl control, TabPage tp)
        {
            ShowTabPage(control, tp, control.TabPages.Count);
        }


        public static void ShowTabPage(this TabControl control, TabPage tp, int index)
        {
            if (control.TabPages.Contains(tp)) return;
            InsertTabPage(control, tp, index);
        }


        private static void InsertTabPage(TabControl control, TabPage tabpage, int index)
        {
            if (index > control.TabCount)
                index = control.TabCount;
            //if (index < 0 || index > control.TabCount)
            //    throw new ArgumentException("Index out of Range.");
            control.TabPages.Add(tabpage);
            if (index < control.TabCount - 1)
                do
                {
                    SwapTabPages(control, tabpage, (control.TabPages[control.TabPages.IndexOf(tabpage) - 1]));
                }
                while (control.TabPages.IndexOf(tabpage) != index);
            control.SelectedTab = tabpage;
        }


        private static void SwapTabPages(TabControl control, TabPage tp1, TabPage tp2)
        {
            if (control.TabPages.Contains(tp1) == false || control.TabPages.Contains(tp2) == false)
                throw new ArgumentException("TabPages must be in the TabControls TabPageCollection.");

            int Index1 = control.TabPages.IndexOf(tp1);
            int Index2 = control.TabPages.IndexOf(tp2);
            control.TabPages[Index1] = tp2;
            control.TabPages[Index2] = tp1;

            //Uncomment the following section to overcome bugs in the Compact Framework
            //tabControl1.SelectedIndex = tabControl1.SelectedIndex; 
            //string tp1Text, tp2Text;
            //tp1Text = tp1.Text;
            //tp2Text = tp2.Text;
            //tp1.Text=tp2Text;
            //tp2.Text=tp1Text;

        }
    }
}
